package com.xiaoyao.novel.service;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

public class ClickService {
	static Logger logger = Logger.getLogger(ClickService.class);
	static BookService bookService = new BookService();
	static Map<Integer, Integer> bookClickMap = new HashMap<Integer, Integer>();
	static final int MAX_CLICK = 2000;
	static final int MAX_SIZE = 100;

	/**
	 * 小说的点击
	 * 
	 * @param bookId
	 */
	public static void click(int bookId) {
		Integer count = bookClickMap.get(bookId);
		if (count == null) {
			count = 0;
		}
		bookClickMap.put(bookId, count + 1);
		if (count >= MAX_CLICK || bookClickMap.size()>=MAX_SIZE) {
			new Thread() {
				public void run() {
					save();
				};
			}.start();
		} 
	}

	/**
	 * 保存 //一次保存多个
	 */
	public static void save() {
		Map<Integer, Integer> map=new HashMap<Integer, Integer>(bookClickMap); 
		bookClickMap = new HashMap<Integer, Integer>();
		logger.warn("保存点击记录!"+map);
//		bookService.calcClick(map); // 不能批量.速度更慢
		for (Entry<Integer, Integer> entry : map.entrySet()) {
			bookService.calcClick(entry.getKey(), entry.getValue());
		}
	}

}
